﻿//globals
var $status = {};
$status.failures = [];
$status.successes = [];

var _ignoreServerStatuses = false;

function ToggleStatuses(hide) {

    if (hide === true)//seems obvious but sometimes it could be an object and not True, thereby circumventing the boolean logic attempted
    {
        $(".success").hide();
        $(".fail").hide();
        $("#SuccessFlyout").hide();
        $("#FailFlyout").hide();
    }
    else {

        $('#StatusBar').css({
            "right": $('#content').hasScrollBar() ? "16px" : "0px"
        });

        var offsetTop = 21;

        $('#SuccessFlyout').offset({ top: $('#SuccessFlyout').offset().top == 0 ? offsetTop : $('#SuccessFlyout').offset().top});
        $('#FailFlyout').offset({ top: $('#FailFlyout').offset().top == 0 ? offsetTop : $('#FailFlyout').offset().top });

        if (!_ignoreServerStatuses) {
            RefreshServerStatuses(); // once RefreshServerStatuses() gets the new statuses from the server it will call ToggleStatuses_HandleDisplaying() to display the new statuses
        }
        else {
            ToggleStatuses_HandleDisplaying();
        }

    }
}

// Helper function for ToggleStatuses().  This function is called once the RefreshServerStatuses() json callback comes back with the new statuses.
// We needed to break this logic out of ToggleStatuses() because of the callback nature of RefreshServerStatuses().
function ToggleStatuses_HandleDisplaying() {

    $(".success").toggle($status.successes != undefined && $status.successes.length > 0);
    $(".fail").toggle($status.failures != undefined && $status.failures.length > 0);

    $("#FailFlyout").hide(); // hide the flyout just in case it is currently being shown and there are no errors to show anymore (see bug 5047)
    if ($status.failures) {
        $("#StatusBar").show();
        $("#FailFlyout > .ItemList").empty().append(GetItemsUL($status.failures)[0]);

        if ($status.failures.length > 0) {
            $("#FailFlyout").show();
        }
    }

    if ($status.successes) {
        setTimeout(function () {
            $("#StatusBar").fadeOut(1000);
            }, 10000);
        $("#StatusBar").show();
        $("#SuccessFlyout > .ItemList").empty();
        $("#SuccessFlyout > .ItemList").append(GetItemsUL($status.successes)[0]);
    }

}

function GetItemsUL(items) {
    $list = $("<ul/>", {});
    for (itemIndex = 0; itemIndex < eval(items).length; itemIndex++) {
        var message;
        try{
            message = $.parseJSON(items[itemIndex]).message;
        }
        catch (err1) {
            message = items[itemIndex].message
        }

        $list.append($("<li/>", { "html": message }));
    }

    return $list;
}

$(function () {

    //for pages without an update panel
    if ($("#panBodyNoUpdateContent").children().length > 0) {
        ToggleStatuses();
    }

    $(".fail").click(function () { $("#FailFlyout").toggle() });
    $(".success").click(function () { $("#SuccessFlyout").toggle() });

    //for pages with an update panel
    Sys.Application.add_load(ToggleStatuses);
});

function clearStatusList(status) {
    if (status == "fail" || status === undefined) {
        $status.failures = [];
        ToggleStatuses(true);
        $(".success").toggle($status.successes != undefined && $status.successes.length > 0);
    }

    if (status == "success" || status === undefined) {
        $status.successes = [];
        ToggleStatuses(true);
        $(".fail").toggle($status.failures != undefined && $status.failures.length > 0);
    }
}

function RefreshServerStatuses() {

    var successMessagesOnly = []
    $($status.successes).each(function () {
        successMessagesOnly.push(this.message);
    });

    var failureMessagesOnly = []
    $($status.failures).each(function () {
        failureMessagesOnly.push(this.message);
    });

    var request = { "FunctionName": "RefreshServerStatuses",
        "Data": [{ "Id": "Successes",
            "Key": "Successes",
            "Values": successMessagesOnly
        },
                { "Id": "Failures",
                    "Key": "Failures",
                    "Values": failureMessagesOnly
                }]
    };


    var responseDelegate = function (jsonResponse) {
        $status.failures = jsonResponse.Data.Failures;
        $status.successes = jsonResponse.Data.Successes;

        ToggleStatuses_HandleDisplaying();
    };

    var requestManager = new RequestManager(request, responseDelegate, true);
    requestManager.ExecuteRequest();

}

function ShowValidationErrors() {
    if ($status !== undefined) {
        $status.failures = [];
        clearStatusList("fail");
        ToggleStatuses(true);
        var show = false;
        //iterate through the validators that aren't already in the status failures list and add them
        $(Page_Validators).filter(function (validator) {
            return $status.failures.length == 0 || $status.failures.filter(function (failure) {
                failure.message == validator.errormessage
            }) == [];
        }).each(function () {
            var validator = $(this)[0];
            if (!validator.isvalid) {
                $failure = { "type": "validation", "message": validator.errormessage };
                $status.failures.push($failure);
                _ignoreServerStatuses = true;
                show = true;
            }
        });
        if (show) {
            $("#FailFlyout").show();
            ToggleStatuses();
        }
    }
}
